﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using Marbles.Core.Helpers;
using Marbles.Core.Web.MVC.Views;

namespace Marbles.Core.Web.State
{
    public class SessionStatePersistanceManager : IStatePersistanceManager
    {

        private CompressionMethod _CompressionMethod = CompressionMethod.None;

        public SessionStatePersistanceManager()
        {
            this._CompressionMethod = CompressionMethod.None;
        }

        public SessionStatePersistanceManager(CompressionMethod CompressionMethod)
        {
            this._CompressionMethod = CompressionMethod;
        }
       
        public string SavePageStateToPersistenceMedium(object state, ViewBase Page)
        {
            StringWriter sw = new StringWriter();
            LosFormatter ser = new LosFormatter();
            ser.Serialize(sw, state);
            sw.Flush();

            if (this._CompressionMethod == CompressionMethod.None)
            {
                HttpContext.Current.Session[Page.ViewStateKey] = sw.ToString();
            }
            else
            {
                HttpContext.Current.Session[Page.ViewStateKey] = Compression.Compress(sw.ToString(), this._CompressionMethod);
            }
          
          
            return Page.ViewStateKey;
        }

        public object LoadPageStateFromPersistenceMedium(ViewBase Page)
        {
            LosFormatter ser = new LosFormatter();
            string value = string.Empty;
            if (HttpContext.Current.Session[Page.ViewStateKey] != null)
            {
                value = HttpContext.Current.Session[Page.ViewStateKey] as string;
                HttpContext.Current.Session[Page.ViewStateKey] = null;
                HttpContext.Current.Session.Remove(Page.ViewStateKey);
            }

            if (this._CompressionMethod != CompressionMethod.None)
            {
                value = Compression.Decompress(value, this._CompressionMethod);
            }
          
            return ser.Deserialize(value);
        }
    }
}
